using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace cb0tServer
{
    class SCASObject
    {
        public Socket socket = null;
        public int session_spawn_time = 0;
        public int receive_fails = 0;
        public ushort id;
        public bool logged_in;
        public Guid scas_guid = new Guid();
        public ushort scas_version = 0;

        private List<byte> inbound_buffer = new List<byte>(); // for dumping received data
        private Queue<byte[]> outbound_buffer = new Queue<byte[]>(); // for queuing packets

        public SCASObject() { }

        public SCASObject(Socket socket, int id, int session_spawn_time)
        {
            this.socket = socket;
            this.socket.Blocking = false;
            this.logged_in = false;
            this.id = (ushort)id;
            this.session_spawn_time = session_spawn_time;
        }

        public bool IsSet() // socket is occupied?
        {
            return this.socket != null;
        }

        public void Disconnect() // kill scas
        {
            this.logged_in = false;
            this.DispatchOutboundPackets(); // try to send outstanding packets

            try
            {
                this.socket.Disconnect(false); // disconnect
            }
            catch { }

            this.socket = null; // delete socket
        }

        public void DispatchOutboundPackets() // send all pending packets
        {
            while (this.outbound_buffer.Count > 0)
            {
                try
                {
                    this.socket.Send(this.outbound_buffer.Peek());
                    this.outbound_buffer.Dequeue();
                }
                catch { return; }
            }
        }

        public void AddReceivedBytes(byte[] data) // add to received data dump
        {
            this.inbound_buffer.AddRange(data);
        }

        public void RemoveReceivedBytes(int count) // trim received data dump
        {
            this.inbound_buffer.RemoveRange(0, count);
        }

        public byte[] GetReceivedBytes() // retrieve received data dump
        {
            if (this.inbound_buffer.Count > 3)
            {
                return this.inbound_buffer.ToArray();
            }

            return null;
        }

        public void SendOutboundPacket(byte[] data) // add packet to outbound buffer
        {
            this.outbound_buffer.Enqueue(data);
        }
    }
}
